package com.yonyou.gmmc.service.forum.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.marketing.common.DloadImgUtil;
import org.marketing.common.dto.forum.ForumReplyDto;
import org.marketing.common.dto.forum.ForumTopicDto;
import org.marketing.common.dto.forum.ForumTopicImgDto;
import org.marketing.common.dto.forum.ForumTypeDto;
import org.marketing.common.exception.ServiceBizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.infoservice.filestore.FileStore;
import com.yonyou.gmmc.service.forum.constant.ForumConstant;
import com.yonyou.gmmc.service.forum.dao.TmForumBoardMapper;
import com.yonyou.gmmc.service.forum.dao.TmForumImgMapper;
import com.yonyou.gmmc.service.forum.dao.TmNewsActivityInfoMapper;
import com.yonyou.gmmc.service.forum.dao.TtForumReadingMapper;
import com.yonyou.gmmc.service.forum.dao.TtForumReplyMapper;
import com.yonyou.gmmc.service.forum.dao.TtForumTopicImgMapper;
import com.yonyou.gmmc.service.forum.dao.TtForumTopicMapper;
import com.yonyou.gmmc.service.forum.dao.TtForumTranspondMapper;
import com.yonyou.gmmc.service.forum.model.ImgListDto;
import com.yonyou.gmmc.service.forum.model.TmForumBoard;
import com.yonyou.gmmc.service.forum.model.TmForumImg;
import com.yonyou.gmmc.service.forum.model.TmNewsActivityInfo;
import com.yonyou.gmmc.service.forum.model.TtForumReading;
import com.yonyou.gmmc.service.forum.model.TtForumReply;
import com.yonyou.gmmc.service.forum.model.TtForumTopic;
import com.yonyou.gmmc.service.forum.model.TtForumTopicImg;
import com.yonyou.gmmc.service.forum.model.TtForumTranspond;
import com.yonyou.gmmc.service.forum.util.EmojiUtil;


@Service
@Transactional
public class ForumService {
	
	private static Logger logger = LoggerFactory.getLogger(ForumService.class);
	
	@Autowired
	private TtForumTopicMapper ttForumTopicMapper;
	
	@Autowired
	private TtForumReplyMapper ttForumReplyMapper;
	
	@Autowired
	private TtForumTopicImgMapper ttForumTopicImgMapper;
	
	@Autowired
	private TmForumBoardMapper tmForumBoardMapper;
	
	@Autowired
	private TmForumImgMapper tmForumImgMapper;

	@Autowired
	private TtForumReadingMapper ttForumReadingMapper;
	
	@Autowired
	private TtForumTranspondMapper ttForumTranspondMapper;
	
	@Autowired
	private TmNewsActivityInfoMapper tmNewsActivityInfoMapper;
	
	@Autowired
	private ForumServiceInterface forumServiceInterface;
	
	
	/**
	 * 查询版块类型
	 * @return
	 */
	public List<ForumTypeDto> getBoardType() throws Exception {
		try{
			logger.info("查询版块类型开始");
			List<ForumTypeDto> dtoList=ttForumTopicMapper.getBoardType();
			logger.info("查询版块类型结束");
			return dtoList;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	
	/**
	 * 查询版块类型PC
	 * @return
	 */
	public List<ForumTypeDto> getBoardTypePC() throws Exception {
		try{
			logger.info("查询版块类型PC开始");
			List<ForumTypeDto> dtoList=ttForumTopicMapper.getBoardTypePC();
			logger.info("查询版块类型PC结束");
			return dtoList;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	
	/**
	 * 查询更多版块列表
	 * @return
	 */
	public List<ForumTypeDto> queryBoardList() throws Exception {
		try{
			logger.info("查询更多版块列表开始");
			List<ForumTypeDto> dtoList=ttForumTopicMapper.queryBoardList();
			logger.info("查询更多版块列表结束");
			return dtoList;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	

	/**
	 * 获取标题列表
	 * @param queryMap
	 * @param openId 
	 * @return
	 */
	public PageInfo<ForumTopicDto> getTopicList(Map<String, Object> queryMap, String openId) throws Exception {
		try{
			if(queryMap.get("hotType")!=null){
				if(!queryMap.get("hotType").equals(0) && !queryMap.get("hotType").equals(1) && !queryMap.get("hotType").equals(7) && !queryMap.get("hotType").equals(10)){
					queryMap.remove("hotType");
					queryMap.put("hotType", 10);
				}
			}
			// 查询标题列表
			Page<ForumTopicDto> ss = PageHelper.startPage(Integer.parseInt(queryMap.get("pageNum").toString()),
					Integer.parseInt(queryMap.get("pageSize").toString()));
			logger.info("ss为————" + ss);
			List<ForumTopicDto> pd = ttForumTopicMapper.getTopicList(queryMap);
			if(pd!=null){
				for(ForumTopicDto ftDto : pd){
					//替换时间格式
					Date postTime=ftDto.getPostTime();
					String postTimeStr=transFormTime(postTime);
					ftDto.setPostTimeStr(postTimeStr);
					
					logger.info("帖子内容："+ftDto.getTopicContent());
					String content = EmojiUtil.emojiConverterUnicodeStr(ftDto.getTopicContent());
					logger.info("编译后内容："+content);
					ftDto.setTopicContent(content);
					
					//判断openId
					String topicOpenId=ftDto.getOpenId();
					logger.info("openId:"+openId);
					logger.info("topicOpenId:"+topicOpenId);
					if(openId==null){
						openId="0";
					}
					if(openId==topicOpenId||openId.equals(topicOpenId)){
						logger.info("openId相同：返回ifMy为1");
						ftDto.setIfMy(1);
					}else{
						logger.info("openId不相同，返回ifMy为0：");
						ftDto.setIfMy(0);
					}
				}
			}
			//logger.info("pd为————" + pd.toString());
			PageInfo<ForumTopicDto> page = new PageInfo<>(pd);
			//logger.info("page为————" + page);
			return page;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	/**
	 * 查询回复列表
	 * @param queryMap
	 * @param openId 
	 * @return
	 */
	public PageInfo<TtForumReply> getReplyList(Map<String, Object> queryMap, String openId) throws Exception {
		try{
			// 查询回复列表
			Page<TtForumReply> ss = PageHelper.startPage(Integer.parseInt(queryMap.get("pageNum").toString()),
					Integer.parseInt(queryMap.get("pageSize").toString()));
			//logger.info("ss为————" + ss);
			List<TtForumReply> pd = ttForumReplyMapper.getReplyList(queryMap);
			
			if(pd!=null){
				for(TtForumReply ftDto : pd){
					String content = EmojiUtil.emojiConverterUnicodeStr(ftDto.getReplyContent());
					ftDto.setReplyContent(content);
					
					//判断openId
					String replyOpenId=ftDto.getOpenId();
					logger.info("openId:"+openId);
					logger.info("replyOpenId:"+replyOpenId);
					if(openId==replyOpenId||openId.equals(replyOpenId)){
						logger.info("openId相同：返回ifMy为1");
						ftDto.setIfMy(1);
					}else{
						logger.info("openId不相同，返回ifMy为0：");
						ftDto.setIfMy(0);
					}
				}
			}
			
			//logger.info("pd为————" + pd.toString());
			PageInfo<TtForumReply> page = new PageInfo<>(pd);
			//logger.info("page为————" + page);
			return page;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	
	/**
	 * 帖子详情
	 * @param queryMap
	 * @return
	 */
	public ForumTopicDto topicDetails(Long topicId,String openId) throws Exception {
		try{
			Map<String,Object> result=new HashMap<String,Object>();
			logger.info("查询我的论坛开始，topicId为："+topicId+",openId:"+openId);
			ForumTopicDto resultMap=ttForumTopicMapper.topicDetails(topicId);
			//时间处理
			Date postTime=resultMap.getPostTime();
			String postTimeStr=transFormTime(postTime);
			resultMap.setPostTimeStr(postTimeStr);
			
			logger.info("帖子内容："+resultMap.getTopicContent());
			String topicContent = EmojiUtil.emojiConverterUnicodeStr(resultMap.getTopicContent());
			logger.info("反编译帖子内容："+topicContent);
			resultMap.setTopicContent(topicContent);
			List<ForumReplyDto> forumReplyList=resultMap.getForumReplyDto();
			if(forumReplyList!=null){
				for(ForumReplyDto forumReplyDto : forumReplyList){
					Date replyPostTime=forumReplyDto.getPostTime();
					String replyPostTimeStr=transFormTime(replyPostTime);
					forumReplyDto.setPostTimeStr(replyPostTimeStr);
					
					logger.info("回复内容："+forumReplyDto.getReplyContent());
					String content = EmojiUtil.emojiConverterUnicodeStr(forumReplyDto.getReplyContent());
					logger.info("反编译的回复内容："+content);
					forumReplyDto.setReplyContent(content);
					
				}
			}
			
			String topicOpenId=resultMap.getOpenId();
			if(openId==null){
				logger.info("openId不相同，返回ifMy为0：");
				resultMap.setIfMy(0);
			}else{
				if(openId==topicOpenId||openId.equals(topicOpenId)){
					logger.info("openId相同：返回ifMy为1");
					resultMap.setIfMy(1);
				}else{
					logger.info("openId不相同，返回ifMy为0：");
					resultMap.setIfMy(0);
				}
			}
			
			
			if(forumReplyList!=null){
				for(ForumReplyDto ftDto : forumReplyList){
					//判断openId
					String replyOpenId=ftDto.getOpenId();
					logger.info("openId:"+openId);
					logger.info("replyOpenId:"+replyOpenId);
					if(openId==null){
						logger.info("openId不相同，返回ifMy为0：");
						ftDto.setIfMy(0);
					}else{
						if(openId==replyOpenId||openId.equals(replyOpenId)){
							logger.info("openId相同：返回ifMy为1");
							ftDto.setIfMy(1);
						}else{
							logger.info("openId不相同，返回ifMy为0：");
							ftDto.setIfMy(0);
						}
					}
				}
			}
			
			
			//增加阅读数
			TtForumReading tmForumReading = new TtForumReading();
			Date newDate=new Date();
//			logger.info("通过openId查询潜客ID，openId:"+openId);
			Long potentialUserId=ttForumTopicMapper.queryPotentialUserId(openId);
			if(potentialUserId==null){
				logger.info("通过openId没有找到potentialUserId，非菱悦会用户");
				potentialUserId=10011004L;//非菱悦会ID
				result.put("flag", 0);
				result.put("msg", "非菱悦会用户");
				resultMap.setReadUserType(0);
			}else{
				logger.info("菱悦会用户");
				result.put("flag", 1);
				result.put("msg", "菱悦会用户");
				resultMap.setReadUserType(1);
			}
			logger.info("potentialUserId:"+potentialUserId);
			logger.info("查询是否存在该条记录，topicId:"+topicId+",potentialUserId:"+potentialUserId);
			tmForumReading.setPotentialUserId(potentialUserId);
			tmForumReading.setTopicId(topicId);
			List<TtForumReading> readingList=ttForumReadingMapper.select(tmForumReading);
			if(readingList==null || readingList.size()==0){
				tmForumReading.setReadingNum(1L);
				tmForumReading.setCreateDate(newDate);
				tmForumReading.setCreateBy(potentialUserId);
				ttForumReadingMapper.insertSelective(tmForumReading);
				logger.info("增加阅读数量成功！");
			}else{
				tmForumReading.setUpdateDate(newDate);
				tmForumReading.setUpdateBy(potentialUserId);
				ttForumReadingMapper.updateReadingNum(tmForumReading);
				logger.info("该用户已阅读本标题，阅读量加1！");
			}
			result.put("resultMap", resultMap);
			logger.info("查询帖子详情结束");
			return resultMap;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	
	
	/**
	 * 我的论坛
	 * @param openId
	 * @return
	 */
	public Map<String, Object> queryMyForum(String openId) throws Exception {
		try{
//			logger.info("查询我的论坛开始，openId为："+openId);
			Map<String, Object> resultMap=ttForumTopicMapper.queryMyForum(openId);
			logger.info("查询我的论坛结束");
			return resultMap;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	/**
	 * 我的帖子
	 * @param queryMap
	 * @param openId 
	 * @return
	 */
	public PageInfo<ForumTopicDto> queryMyTopic(Map<String, Object> queryMap, String openId) throws Exception {
		try{
			// 查询我的帖子列表
			Page<ForumTopicDto> ss = PageHelper.startPage(Integer.parseInt(queryMap.get("pageNum").toString()),
					Integer.parseInt(queryMap.get("pageSize").toString()));
//			logger.info("ss为————" + ss);
			List<ForumTopicDto> pd = ttForumTopicMapper.getTopicList(queryMap);
			if(pd!=null){
				for(ForumTopicDto ftDto : pd){
					//替换时间格式
					Date postTime=ftDto.getPostTime();
					String postTimeStr=transFormTime(postTime);
					ftDto.setPostTimeStr(postTimeStr);
					
					//转义表情
					String content = EmojiUtil.emojiConverterUnicodeStr(ftDto.getTopicContent());
					ftDto.setTopicContent(content);
					
					//判断openId
					String topicOpenId=ftDto.getOpenId();
					logger.info("openId:"+openId);
					logger.info("topicOpenId:"+topicOpenId);
					if(openId==topicOpenId||openId.equals(topicOpenId)){
						logger.info("openId相同：返回ifMy为1");
						ftDto.setIfMy(1);
					}else{
						logger.info("openId不相同，返回ifMy为0：");
						ftDto.setIfMy(0);
					}
				}
			}
//			logger.info("pd为————" + pd.toString());
			PageInfo<ForumTopicDto> page = new PageInfo<>(pd);
			logger.info("page为————" + page);
			return page;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	
	
	/**
	 * 我的评论
	 * @param queryMap
	 * @param openId 
	 * @return
	 */
	public PageInfo<ForumTopicDto> queryMyReply(Map<String, Object> queryMap, String openId) throws Exception {
		try{
			// 查询我的评论列表
			Page<TtForumReply> ss = PageHelper.startPage(Integer.parseInt(queryMap.get("pageNum").toString()),
					Integer.parseInt(queryMap.get("pageSize").toString()));
			logger.info("ss为————" + ss);
			List<ForumTopicDto> pd = ttForumReplyMapper.queryMyReply(queryMap);
			
			if(pd!=null){
				for(ForumTopicDto ftDto : pd){
					//替换时间格式
					Date postTime=ftDto.getPostTime();
					String postTimeStr=transFormTime(postTime);
					ftDto.setPostTimeStr(postTimeStr);
					
					//转义表情
					String topicContent = EmojiUtil.emojiConverterUnicodeStr(ftDto.getTopicContent());
					ftDto.setTopicContent(topicContent);
					
					//判断openId
					String topicOpenId=ftDto.getOpenId();
					logger.info("openId:"+openId);
					logger.info("topicOpenId:"+topicOpenId);
					if(openId==topicOpenId||openId.equals(topicOpenId)){
						logger.info("openId相同：返回ifMy为1");
						ftDto.setIfMy(1);
					}else{
						logger.info("openId不相同，返回ifMy为0：");
						ftDto.setIfMy(0);
					}
					List<ForumReplyDto> forumReplyDto = ftDto.getForumReplyDto(); 
					if(forumReplyDto!=null){
						for(ForumReplyDto frDto : forumReplyDto){
							//替换时间格式
							Date postTimeReply=frDto.getPostTime();
							String postTimeReplyStr=transFormTime(postTimeReply);
							frDto.setPostTimeStr(postTimeReplyStr);
							
							//转义表情
							String content = EmojiUtil.emojiConverterUnicodeStr(frDto.getReplyContent());
							frDto.setReplyContent(content);
							
							//判断openId
							String topicOpenIdReply=frDto.getOpenId();
							logger.info("openId:"+openId);
							logger.info("topicOpenIdReply:"+topicOpenIdReply);
							if(openId==topicOpenIdReply||openId.equals(topicOpenIdReply)){
								logger.info("openId相同：返回ifMy为1");
								frDto.setIfMy(1);
							}else{
								logger.info("openId不相同，返回ifMy为0：");
								frDto.setIfMy(0);
							}
						}
					}
				}
			}
			
			logger.info("pd为————" + pd.toString());
			PageInfo<ForumTopicDto> page = new PageInfo<>(pd);
			logger.info("page为————" + page);
			return page;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	
	/**
	 * 我的转发
	 * @param queryMap
	 * @return
	 */
	public PageInfo<ForumTopicDto> queryMyTranspond(Map<String, Object> queryMap,String openId) throws Exception {
		try{
			//logger.info("openId:"+openId);
			//根据openId获取potentialUserId
			Long potentialUserId=ttForumTopicMapper.queryPotentialUserId(openId);
			//logger.info("potentialUserId:"+potentialUserId);
			queryMap.put("potentialUserId", potentialUserId);
			// 查询我的转发列表
			Page<ForumTopicDto> ss = PageHelper.startPage(Integer.parseInt(queryMap.get("pageNum").toString()),
					Integer.parseInt(queryMap.get("pageSize").toString()));
			logger.info("ss为————" + ss);
			List<ForumTopicDto> pd = ttForumTopicMapper.queryMyTranspond(queryMap);
			
			if(pd!=null){
				for(ForumTopicDto ftDto : pd){
					//替换时间格式
					Date postTime=ftDto.getPostTime();
					String postTimeStr=transFormTime(postTime);
					ftDto.setPostTimeStr(postTimeStr);
					
					//判断openId
					String topicOpenId=ftDto.getOpenId();
					logger.info("openId:"+openId);
					logger.info("topicOpenId:"+topicOpenId);
					if(openId==topicOpenId||openId.equals(topicOpenId)){
						logger.info("openId相同：返回ifMy为1");
						ftDto.setIfMy(1);
					}else{
						logger.info("openId不相同，返回ifMy为0：");
						ftDto.setIfMy(0);
					}
				}
			}
			
			logger.info("pd为————" + pd.toString());
			PageInfo<ForumTopicDto> page = new PageInfo<>(pd);
			logger.info("page为————" + page);
			return page;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	
	
	/**
	 * 发帖
	 * @param queryMap
	 * @return
	 */
	public Map<String, Object> publishTopic(String openId,TtForumTopic tmForumTopic, HttpServletRequest request)  throws Exception {
		try{
			Map<String, Object> result = new HashMap<String, Object>();
			//定义帖子图片结合
			List<TtForumTopicImg> topicImgList=new ArrayList<TtForumTopicImg>();
			
			//转义表情
			String content = EmojiUtil.emojiConverterToAlias(tmForumTopic.getTopicContent());
			tmForumTopic.setTopicContent(content);
			
			//通过openId获取PotentialUserId
			logger.info("openId:"+openId);
			Long potentialUserId=ttForumTopicMapper.queryPotentialUserId(openId);
			logger.info("potentialUserId:"+potentialUserId);
			//获取帖子自增ID
			Long topicId=ttForumTopicMapper.queryTopicId();
			logger.info("topicId:"+topicId);
			Date newDate=new Date();
			Long ifTop=0L;
			Long ifessece=0L;
			Short deleteFlag=0;
			//多文件上传
			List<MultipartFile> imgFiles = ((MultipartHttpServletRequest) request)
			        .getFiles("imgFile");
			    MultipartFile imgFile = null;
			    for (int i = 0; i < imgFiles.size(); ++i) {
			    	imgFile = imgFiles.get(i);
			      if (!imgFile.isEmpty()) {
			        try {
			          // 获取上传文件的路径
			          String uploadFilePath = imgFile.getOriginalFilename();
			          logger.info("uploadFilePath:"+uploadFilePath);
			          // 截取上传文件的文件名
			          String uploadFileName = uploadFilePath
			              .substring(uploadFilePath.lastIndexOf('\\') + 1,
			                  uploadFilePath.indexOf('.'));
			          logger.info("uploadFileName:"+uploadFileName);
			          // 截取上传文件的后缀
			          String uploadFileSuffix = uploadFilePath.substring(
			              uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
			          logger.info("uploadFileSuffix:"+uploadFileSuffix);
			          //上传
			          String imgName = FileStore.getInstance().write("nd02", "fs01", uploadFileName+"."+uploadFileSuffix,imgFile.getBytes());
			          logger.info("图片名imgName:"+imgName);
			          String imgURL="";
			          imgURL = FileStore.getInstance().getDomainURL(imgName);
			          logger.info("图片路径imgURL:"+imgURL);
			          logger.info("文件上传成功");
			          TtForumTopicImg tmForumTopicImg=new TtForumTopicImg();
			          tmForumTopicImg.setTopicId(topicId);
			          logger.info("topicId:"+topicId);
			          tmForumTopicImg.setTopicImgPath(imgURL);
			          tmForumTopicImg.setCreateDate(newDate);
			          tmForumTopicImg.setCreateBy(potentialUserId);
			          logger.info("potentialUserId:"+potentialUserId);
			          topicImgList.add(tmForumTopicImg);
			        } catch (Exception e) {
			        	logger.error(e.getMessage(), e);
						throw new ServiceBizException(e.getMessage(), e);
			        } 
			      } else {
			        logger.info("上传文件为空");
			      }
			    }
			    //保存帖子实体
			    tmForumTopic.setTopicId(topicId);
			    tmForumTopic.setPotentialUserId(potentialUserId);
			    tmForumTopic.setUserType(ForumConstant.WX_USER);
			    tmForumTopic.setPostTime(newDate);
			    tmForumTopic.setIfTop(ifTop);
			    tmForumTopic.setIfEssence(ifessece);
			    tmForumTopic.setCreateDate(newDate);
			    tmForumTopic.setCreateBy(potentialUserId);
			    tmForumTopic.setDeleteFlag(deleteFlag);
			    
			    if(!topicImgList.isEmpty() && topicImgList.size()>0){
			    	for(TtForumTopicImg tmFTImg:topicImgList){
			    		ttForumTopicImgMapper.insertSelective(tmFTImg);
			    		logger.info("保存帖子图片实体完成");
			    	}
			    }
			    ttForumTopicMapper.insertSelective(tmForumTopic);
			    logger.info("保存帖子实体完成");
			    result.put("flag", 1);
	            result.put("msg", "发帖成功！");
	            return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	
	/**
	 * 上传图片
	 * @param random 
	 * @param request
	 * @param imgFiles2 
	 * @return
	 */
	public Map<String, Object> uploadImg(String openId,ImgListDto imgListDto) {
		//InputStream inputStream = null;
        //ByteArrayOutputStream output = null;
		try{
            String token = forumServiceInterface.Token();
            logger.info("获取到的TOKEN为："+token);

			Long boardId=imgListDto.getBoardId();
			Integer random=imgListDto.getRandom();
			List<String> imgList=imgListDto.getImgList();
			Map<String, Object> result = new HashMap<String, Object>();
			Date newDate=new Date();
			Long ifTop=0L;
			Long ifessece=0L;
			Short deleteFlag=2;
			//通过openId获取PotentialUserId
			logger.info("openId:"+openId);
			Long potentialUserId=ttForumTopicMapper.queryPotentialUserId(openId);
			logger.info("potentialUserId:"+potentialUserId);
			
			Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("potentialUserId", potentialUserId);
			queryMap.put("random", random);
			Long topicId=ttForumTopicMapper.queryTopicIdR(queryMap);
			if(topicId==null){
				
				logger.info("没有查询到已存在的topicId，新建帖子");
				
				
				ttForumTopicMapper.deleteTopicImg(potentialUserId);
				logger.info("删除帖子图片成功");
				ttForumTopicMapper.deleteTopic(potentialUserId);
				logger.info("删除帖子成功");
				//获取帖子自增ID
				Long topicIdSeq=ttForumTopicMapper.queryTopicId();
				logger.info("topicId:"+topicIdSeq);
				
				
				TtForumTopic  ttForumTopic=new TtForumTopic();
				//保存帖子实体
				ttForumTopic.setBoardId(boardId);
				ttForumTopic.setTopicId(topicIdSeq);
				ttForumTopic.setPotentialUserId(potentialUserId);
				ttForumTopic.setUserType(ForumConstant.WX_USER);
				ttForumTopic.setPostTime(newDate);
				ttForumTopic.setIfTop(ifTop);
				ttForumTopic.setIfEssence(ifessece);
				ttForumTopic.setCreateDate(newDate);
				ttForumTopic.setCreateBy(potentialUserId);
				ttForumTopic.setDeleteFlag(deleteFlag);
				ttForumTopic.setRandom(random);
			    
			    ttForumTopicMapper.insertSelective(ttForumTopic);
			    logger.info("插入帖子实体成功");
			    List<String> imgUrls=DloadImgUtil.downloadMedia(imgList,token);
			    List<TtForumTopicImg> topicImgList=new ArrayList<TtForumTopicImg>();
			    String imgUrl=null;
			    if(imgUrls!=null){
			    	for(int i=0;i<imgUrls.size();i++){
				    	imgUrl=imgUrls.get(i);
				    	logger.info("图片路径imgURL:"+imgUrl);
			            TtForumTopicImg tmForumTopicImg=new TtForumTopicImg();
			            tmForumTopicImg.setTopicId(topicIdSeq);
			            logger.info("topicId:"+topicIdSeq);
			            tmForumTopicImg.setTopicImgPath(imgUrl);
			            tmForumTopicImg.setCreateDate(newDate);
			            tmForumTopicImg.setCreateBy(potentialUserId);
			            topicImgList.add(tmForumTopicImg);
				    }
				    logger.info("保存帖子图片实体开始");
				    if(!topicImgList.isEmpty() && topicImgList.size()>0){
				    	for(TtForumTopicImg tmFTImg:topicImgList){
				    		ttForumTopicImgMapper.insertSelective(tmFTImg);
				    		logger.info("保存帖子图片实体完成");
				    	}
				    }
			    }
			    
			    /*String path="a";
			    List<File> imgFiles=DloadImgUtil.downloadMedia(imgList,path);
				//多文件上传
				List<MultipartFile> imgFiles = ((MultipartHttpServletRequest) request)
				        .getFiles("imgFile");
				    File imgFile = null;
				    for (int i = 0; i < imgFiles.size(); ++i) {
				    	imgFile = imgFiles.get(i);
				      if (imgFile.exists() && imgFile.length()!=0) {
				        try {
				          // 获取上传文件的路径
				          String uploadFilePath = imgFile.getOriginalFilename();
				          logger.info("uploadFilePath:"+uploadFilePath);
				          // 截取上传文件的文件名
				          String uploadFileName = uploadFilePath
				              .substring(uploadFilePath.lastIndexOf('\\') + 1,
				                  uploadFilePath.indexOf('.'));
				          logger.info("uploadFileName:"+uploadFileName);
				          // 截取上传文件的后缀
				          String uploadFileSuffix = uploadFilePath.substring(
				              uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
				          logger.info("uploadFileSuffix:"+uploadFileSuffix);
				          
				        	
				          inputStream = new FileInputStream(imgFile);
				          String newFile=null;
				          byte[] buffer = new byte[8096];
				          int length=0;
				          while (-1 != (length = inputStream.read(buffer))) {
				        	  newFile=new String(buffer, 0, length);
				        	  //output.write(buffer, 0, length);
				            }
				          String uploadFileName=imgFile.getName();
				          //上传
				          //String imgName = FileStore.getInstance().write("nd02", "fs01", uploadFileName+"."+uploadFileSuffix,imgFile.getBytes());
				          String imgName = FileStore.getInstance().write("nd02", "fs01", uploadFileName,newFile.getBytes());
				          logger.info("图片名imgName:"+imgName);
				          String imgURL="";
				          imgURL = FileStore.getInstance().getDomainURL(imgName);
				          logger.info("图片路径imgURL:"+imgURL);
				          logger.info("文件上传成功");
				          TtForumTopicImg tmForumTopicImg=new TtForumTopicImg();
				          tmForumTopicImg.setTopicId(topicIdSeq);
				          logger.info("topicId:"+topicIdSeq);
				          tmForumTopicImg.setTopicImgPath(imgURL);
				          tmForumTopicImg.setCreateDate(newDate);
				          tmForumTopicImg.setCreateBy(potentialUserId);
				          topicImgList.add(tmForumTopicImg);
				        } catch (Exception e) {
				        	logger.error(e.getMessage(), e);
							throw new ServiceBizException(e.getMessage(), e);
				        } 
				      } else {
				        logger.info("上传文件为空");
				      }
				    }*/
			    
			}else{
				logger.info("查到已存在的topicId,在原来帖子上新加图片");
				
				
				List<String> imgUrls=DloadImgUtil.downloadMedia(imgList,token);
			    List<TtForumTopicImg> topicImgList=new ArrayList<TtForumTopicImg>();
			    String imgUrl=null;
			    if(imgUrls!=null){
			    	for(int i=0;i<imgUrls.size();i++){
				    	imgUrl=imgUrls.get(i);
				    	logger.info("图片路径imgURL:"+imgUrl);
			            TtForumTopicImg tmForumTopicImg=new TtForumTopicImg();
			            tmForumTopicImg.setTopicId(topicId);
			            logger.info("topicId:"+topicId);
			            tmForumTopicImg.setTopicImgPath(imgUrl);
			            tmForumTopicImg.setCreateDate(newDate);
			            tmForumTopicImg.setCreateBy(potentialUserId);
			            topicImgList.add(tmForumTopicImg);
				    }
				    logger.info("保存帖子图片实体开始");
				    if(!topicImgList.isEmpty() && topicImgList.size()>0){
				    	for(TtForumTopicImg tmFTImg:topicImgList){
				    		ttForumTopicImgMapper.insertSelective(tmFTImg);
				    		logger.info("保存帖子图片实体完成");
				    	}
				    }
			    }
			    
			    
				/*String path="a";
			    List<File> imgFiles=DloadImgUtil.downloadMedia(imgList,path);
			    
				List<TtForumTopicImg> topicImgList=new ArrayList<TtForumTopicImg>();
				//多文件上传
				List<MultipartFile> imgFiles = ((MultipartHttpServletRequest) request)
				        .getFiles("imgFile");
				    File imgFile = null;
				    for (int i = 0; i < imgFiles.size(); ++i) {
				    	imgFile = imgFiles.get(i);
				        try {
				          // 获取上传文件的路径
				          String uploadFilePath = imgFile.getOriginalFilename();
				          logger.info("uploadFilePath:"+uploadFilePath);
				          // 截取上传文件的文件名
				          String uploadFileName = uploadFilePath
				              .substring(uploadFilePath.lastIndexOf('\\') + 1,
				                  uploadFilePath.indexOf('.'));
				          logger.info("uploadFileName:"+uploadFileName);
				          // 截取上传文件的后缀
				          String uploadFileSuffix = uploadFilePath.substring(
				              uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
				          logger.info("uploadFileSuffix:"+uploadFileSuffix);
			        	  inputStream = new FileInputStream(imgFile);
				          String newFile=null;
				          output = new ByteArrayOutputStream();
				          byte[] buffer = new byte[8096];
				          int length=0;
				          while (-1 != (length = inputStream.read(buffer))) {
				        	  //newFile=new String(buffer, 0, length);
				        	  output.write(buffer, 0, length);
				            }
				          String uploadFileName=imgFile.getName();
				          //上传
				          String imgName = FileStore.getInstance().write("nd02", "fs01", uploadFileName,output.toString().getBytes());
				          logger.info("图片名imgName:"+imgName);
				          String imgURL="";
				          imgURL = FileStore.getInstance().getDomainURL(imgName);
				          logger.info("图片路径imgURL:"+imgURL);
				          logger.info("文件上传成功");
				          TtForumTopicImg tmForumTopicImg=new TtForumTopicImg();
				          tmForumTopicImg.setTopicId(topicId);
				          logger.info("topicId:"+topicId);
				          tmForumTopicImg.setTopicImgPath(imgURL);
				          tmForumTopicImg.setCreateDate(newDate);
				          tmForumTopicImg.setCreateBy(potentialUserId);
				          topicImgList.add(tmForumTopicImg);
				        } catch (Exception e) {
				        	logger.error(e.getMessage(), e);
							throw new ServiceBizException(e.getMessage(), e);
				        } 
				    }*/
				
			}
		    result.put("flag", 1);
            result.put("msg", "图片上传成功！");
            return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		} /*finally {
            try {
                if (inputStream != null) inputStream.close();
            } catch (Exception e) {
            }
            try {
                if (output != null) output.close();
            } catch (Exception e) {

            }

        }*/
	}




	/**
	 * 上传帖子内容
	 * @param openId
	 * @param tmForumTopic
	 * @param random 
	 * @return
	 */
	public Map<String, Object> uploadTopic(String openId, TtForumTopic tmForumTopic) {
		try{
			Integer random=tmForumTopic.getRandom();
			Map<String, Object> result = new HashMap<String, Object>();
			//转义表情
			String content = EmojiUtil.emojiConverterToAlias(tmForumTopic.getTopicContent());
			tmForumTopic.setTopicContent(content);
			
			//通过openId获取PotentialUserId
			logger.info("openId:"+openId);
			Long potentialUserId=ttForumTopicMapper.queryPotentialUserId(openId);
			logger.info("potentialUserId:"+potentialUserId);
			
			Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("potentialUserId", potentialUserId);
			queryMap.put("random", random);
			Long topicId=ttForumTopicMapper.queryTopicIdR(queryMap);
			logger.info("根据random查询的topicId为："+topicId);
			Date newDate=new Date();
			Long ifTop=0L;
			Long ifessece=0L;
			Short deleteFlag=0;
			Integer newRandom=0;
			if(topicId==null){
				logger.info("新增帖子开始");;
				//获取帖子自增ID
				Long topicIdSeq=ttForumTopicMapper.queryTopicId();
				logger.info("topicId:"+topicIdSeq);
				tmForumTopic.setTopicId(topicIdSeq);
			    tmForumTopic.setPotentialUserId(potentialUserId);
			    tmForumTopic.setUserType(ForumConstant.WX_USER);
			    tmForumTopic.setPostTime(newDate);
			    tmForumTopic.setIfTop(ifTop);
			    tmForumTopic.setIfEssence(ifessece);
			    tmForumTopic.setCreateDate(newDate);
			    tmForumTopic.setCreateBy(potentialUserId);
			    tmForumTopic.setDeleteFlag(deleteFlag);
			    tmForumTopic.setRandom(newRandom);
			    
			    ttForumTopicMapper.insertSelective(tmForumTopic);
			    logger.info("新增帖子完成");
			}else{
				logger.info("更新帖子开始");
				//保存帖子实体
				tmForumTopic.setTopicId(topicId);
			    tmForumTopic.setPotentialUserId(potentialUserId);
			    tmForumTopic.setUserType(ForumConstant.WX_USER);
			    tmForumTopic.setPostTime(newDate);
			    tmForumTopic.setIfTop(ifTop);
			    tmForumTopic.setIfEssence(ifessece);
			    tmForumTopic.setCreateDate(newDate);
			    tmForumTopic.setCreateBy(potentialUserId);
			    tmForumTopic.setDeleteFlag(deleteFlag);
			    tmForumTopic.setRandom(newRandom);
			    
			    ttForumTopicMapper.updateByPrimaryKeySelective(tmForumTopic);
			    logger.info("更新帖子完成");
			}
		    logger.info("保存帖子实体完成");
		    result.put("flag", 1);
            result.put("msg", "发帖成功！");
            return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	
	
	/**
	 * 获取帖子自增ID
	 * @return
	 * @throws Exception
	 */
	public Long  queryTopicId() throws Exception{
		try{
			//获取帖子自增ID
			Long topicId=ttForumTopicMapper.queryTopicId();
			logger.info("topicId:"+topicId);
			return topicId;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	
	
	/**
	 * 获取potentialUserId
	 * @return
	 * @throws Exception
	 */
	public Long  queryPotentialUserId(String openId) throws Exception{
		try{
			//获取potentialUserId
			Long potentialUserId=ttForumTopicMapper.queryPotentialUserId(openId);
			logger.info("potentialUserId:"+potentialUserId);
			return potentialUserId;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	
	
	/**
	 * 发表回复
	 * @param openId
	 * @param tmForumReply
	 * @return
	 */
	public Map<String, Object> publishReply(String openId, TtForumReply tmForumReply) throws Exception {
		try{
			Map<String, Object> result = new HashMap<String, Object>();
			//通过openId获取PotentialUserId
			logger.info("openId:"+openId);
			Long potentialUserId=ttForumTopicMapper.queryPotentialUserId(openId);
			logger.info("potentialUserId:"+potentialUserId);
			logger.info("回复内容："+tmForumReply.getReplyContent());
			Date newDate=new Date();
			Short deleteFlag=0;
			String content = EmojiUtil.emojiConverterToAlias(tmForumReply.getReplyContent());
			logger.info("转码回复内容："+content);
			tmForumReply.setReplyContent(content);
			tmForumReply.setPotentialUserId(potentialUserId);
			tmForumReply.setUserType(ForumConstant.WX_USER);
			tmForumReply.setCreateBy(potentialUserId);
			tmForumReply.setPostTime(newDate);
			tmForumReply.setCreateDate(newDate);
			tmForumReply.setDeleteFlag(deleteFlag);
			ttForumReplyMapper.insertSelective(tmForumReply);
			result.put("flag", 1);
			result.put("msg", "回复成功！");
			return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}


	/**
	 * PC后台版块管理列表
	 * @param queryMap
	 * @return
	 */
	public PageInfo<TmForumBoard> queryForumBoardPC(Map<String, Object> queryMap) throws Exception {
		try{
			// PC后台版块管理列表
			Page<TmForumBoard> ss = PageHelper.startPage(Integer.parseInt(queryMap.get("pageNum").toString()),
					Integer.parseInt(queryMap.get("pageSize").toString()));
			logger.info("ss为————" + ss);
			List<TmForumBoard> pd = tmForumBoardMapper.queryForumBoardPC(queryMap);
//			logger.info("pd为————" + pd.toString());
			PageInfo<TmForumBoard> page = new PageInfo<>(pd);
			logger.info("page为————" + page);
			return page;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}


	/**
	 * PC后台版块添加
	 * @param tmForumBoard
	 * @param userId
	 * @return
	 */
	public Map<String, Object> addForumBoardPC(TmForumBoard tmForumBoard, String userId) throws Exception {
		try{
			Map<String, Object> result = new HashMap<String, Object>();
			TmForumBoard forumBoard=new TmForumBoard();
			logger.info("userId:"+userId);
			Short deleteFlag=0;
			Date newDate=new Date();
			/*tmForumBoard.setCreateBy(Long.valueOf(userId));
			tmForumBoard.setCreateDate(newDate);
			tmForumBoard.setDeleteFlag(deleteFlag);*/
			
			forumBoard.setBoardName(tmForumBoard.getBoardName());
			forumBoard.setBoardTypeId(tmForumBoard.getBoardTypeId());
			forumBoard.setImgId(tmForumBoard.getImgId());
			forumBoard.setCreateBy(Long.valueOf(userId));
			forumBoard.setCreateDate(newDate);
			forumBoard.setDeleteFlag(deleteFlag);
			
			tmForumBoardMapper.insertSelective(forumBoard);
			result.put("flag", 1);
			result.put("msg", "版块添加成功！");
			return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}


	/**
	 * PC后台版块编辑
	 * @param boardId
	 * @param userId
	 * @return
	 */
	public Map<String, Object> updateForumBoardPC(TmForumBoard tmForumBoard, String userId) throws Exception {
		try{
			Map<String, Object> result = new HashMap<String, Object>();
			TmForumBoard newForumBoard = new TmForumBoard();
			logger.info("userId:"+userId);
			Date newDate=new Date();
			newForumBoard.setBoardId(tmForumBoard.getBoardId());
			newForumBoard.setBoardTypeId(tmForumBoard.getBoardTypeId());
			newForumBoard.setBoardName(tmForumBoard.getBoardName());
			newForumBoard.setImgId(tmForumBoard.getImgId());
			newForumBoard.setUpdateBy(Long.valueOf(userId));
			newForumBoard.setUpdateDate(newDate);
			tmForumBoardMapper.updateByPrimaryKeySelective(newForumBoard);
			result.put("flag", 1);
			result.put("msg", "版块编辑成功！");
			return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	
	/**
	 * PC后台版块删除
	 * @param boardId
	 * @param userId
	 * @return
	 */
	public Map<String, Object> deleteForumBoardPC(Long boardId, String userId) {
		try{
			Map<String, Object> result = new HashMap<String, Object>();
			TmForumBoard newForumBoard = new TmForumBoard();
			logger.info("userId:"+userId);
			Date newDate=new Date();
			Short deleteFlag=1;
			newForumBoard.setBoardId(boardId);
			newForumBoard.setDeleteFlag(deleteFlag);
			newForumBoard.setUpdateBy(Long.valueOf(userId));
			newForumBoard.setUpdateDate(newDate);
			tmForumBoardMapper.updateByPrimaryKeySelective(newForumBoard);
			result.put("flag", 1);
			result.put("msg", "版块删除成功！");
			return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	

	/**
	 * PC后台查询版块图标列表
	 * @return
	 * @throws Exception
	 */
	public List<TmForumImg> queryForumImgPC() throws Exception {
		try{
			List<TmForumImg> result=tmForumImgMapper.queryForumImgPC();
			return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}


	/**
	 * PC后台帖子列表查询
	 * @param queryMap
	 * @return
	 * @throws Exception
	 */
	public PageInfo<ForumTopicDto> queryForumTopicPC(Map<String, Object> queryMap) throws Exception {
		try{
			// PC后台帖子列表查询
			Page<ForumTopicDto> ss = PageHelper.startPage(Integer.parseInt(queryMap.get("pageNum").toString()),
					Integer.parseInt(queryMap.get("pageSize").toString()));
			logger.info("ss为————" + ss);
			List<ForumTopicDto> pd = ttForumTopicMapper.getTopicList(queryMap);
			for(ForumTopicDto forumTopicDto:pd){
				String content = EmojiUtil.emojiConverterUnicodeStr(forumTopicDto.getTopicContent());
				forumTopicDto.setTopicContent(content);
			}
			logger.info("pd为————" + pd.toString());
			PageInfo<ForumTopicDto> page = new PageInfo<>(pd);
			logger.info("page为————" + page);
			return page;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}


	/**
	 * PC后台帖子精华，删除
	 * @param tmForumTopic
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> updateForumTopicPC(TtForumTopic tmForumTopic, String userId) throws Exception {
		try{
			Map<String, Object> result = new HashMap<String, Object>();
			TtForumTopic forumTopic = new TtForumTopic();
			logger.info("userId:"+userId);
			Date newDate=new Date();
			
			/*tmForumTopic.setUpdateBy(Long.valueOf(userId));
			tmForumTopic.setUpdateDate(newDate);*/
			
			forumTopic.setTopicId(tmForumTopic.getTopicId());
			forumTopic.setIfEssence(tmForumTopic.getIfEssence());
			forumTopic.setDeleteFlag(tmForumTopic.getDeleteFlag());
			forumTopic.setUpdateBy(Long.valueOf(userId));
			forumTopic.setUpdateDate(newDate);
			
			ttForumTopicMapper.updateByPrimaryKeySelective(forumTopic);
			result.put("flag", 1);
			result.put("msg", "帖子精华，删除成功！");
			return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	
	 /**
     * PC后台帖子置顶
     * @param queryMap
     * @return
     */
	public Map<String, Object> updateTopicTopPC(Map<String, Object> queryMap) {
		try{
			Map<String, Object> result = new HashMap<String, Object>();
			logger.info("置顶类型ifTop："+queryMap.get("ifTop"));
			Integer ifTop=Integer.valueOf(queryMap.get("ifTop").toString());
			if(ifTop==0){
				logger.info("取消置顶");
				ttForumTopicMapper.cancelTopicTopPC(queryMap);
				result.put("flag", 1);
				result.put("msg", "取消帖子置顶成功！");
			}else if(ifTop==1){
				logger.info("置顶");
				ttForumTopicMapper.updateTopicTopPC(queryMap);
				result.put("flag", 1);
				result.put("msg", "帖子置顶成功！");
			}else {
				logger.info("置顶类型ifTop有误："+ifTop);
				result.put("flag", 0);
				result.put("msg", "帖子置顶出错！");
			}
			return result;
		}catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}



	/**
	 * PC后台查看评论
	 * @param tmForumTopic
	 * @return
	 * @throws Exception
	 */
	public List<TtForumReply> queryForumReplyPC(Long topicId) throws Exception {
		try{
			// 查询评论列表
			logger.info("PC后台查看评论开始");
			Map<String,Object> queryMap=new HashMap<>();
			queryMap.put("topicId", topicId);
			logger.info("topicId:"+topicId);
			List<TtForumReply> result = ttForumReplyMapper.getReplyList(queryMap);
			for(TtForumReply ttForumReply:result){
				String content = EmojiUtil.emojiConverterUnicodeStr(ttForumReply.getReplyContent());
				ttForumReply.setReplyContent(content);
			}
			logger.info("PC后台查看评论结束");
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}


	/**
	 * 统计阅读数量
	 * @param topicId
	 * @param openId
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> saveReadingNum(Long topicId, String openId) throws Exception {
		try{
			Map<String, Object> result = new HashMap<String, Object>();
			TtForumReading tmForumReading = new TtForumReading();
			Date newDate=new Date();
			//logger.info("通过openId查询潜客ID，openId:"+openId);
			Long potentialUserId=ttForumTopicMapper.queryPotentialUserId(openId);
			logger.info("potentialUserId:"+potentialUserId);
			logger.info("查询是否存在该条记录，topicId:"+topicId+",potentialUserId:"+potentialUserId);
			tmForumReading.setPotentialUserId(potentialUserId);
			tmForumReading.setTopicId(topicId);
			List<TtForumReading> readingList=ttForumReadingMapper.select(tmForumReading);
			if(readingList==null || readingList.size()==0){
				tmForumReading.setReadingNum(1L);
				tmForumReading.setCreateDate(newDate);
				tmForumReading.setCreateBy(potentialUserId);
				ttForumReadingMapper.insertSelective(tmForumReading);
				logger.info("增加阅读数量成功！");
				result.put("flag", 1);
				result.put("msg", "增加阅读数量成功！");
			}else{
				tmForumReading.setUpdateDate(newDate);
				tmForumReading.setUpdateBy(potentialUserId);
				ttForumReadingMapper.updateReadingNum(tmForumReading);
				logger.info("该用户已阅读本标题，阅读量加1！");
				result.put("flag", 1);
				result.put("msg", "该用户已阅读本标题，阅读量加1！");
			}
			return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	
	
	/**
	 * 统计转发数量
	 * @param topicId
	 * @param openId
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> saveTranspondNum(Long topicId, String openId) throws Exception {
		try{
			Map<String, Object> result = new HashMap<String, Object>();
			TtForumTranspond tmForumTranspond = new TtForumTranspond();
			Date newDate=new Date();
			logger.info("通过openId查询潜客ID，openId:"+openId);
			Long potentialUserId=ttForumTopicMapper.queryPotentialUserId(openId);
			logger.info("potentialUserId:"+potentialUserId);
			logger.info("查询是否存在该条记录，topicId:"+topicId+",potentialUserId:"+potentialUserId);
			tmForumTranspond.setPotentialUserId(potentialUserId);
			tmForumTranspond.setTopicId(topicId);
			List<TtForumTranspond> transpondList=ttForumTranspondMapper.select(tmForumTranspond);
			if(transpondList==null || transpondList.size()==0){
				tmForumTranspond.setTranspondNum(1L);
				tmForumTranspond.setCreateDate(newDate);
				tmForumTranspond.setCreateBy(potentialUserId);
				ttForumTranspondMapper.insertSelective(tmForumTranspond);
				logger.info("增加转发数量成功！");
				result.put("flag", 1);
				result.put("msg", "增加转发数量成功！");
			}else{
				tmForumTranspond.setUpdateDate(newDate);
				tmForumTranspond.setUpdateBy(potentialUserId);
				ttForumTranspondMapper.updateTranspondNum(tmForumTranspond);
				logger.info("该用户已转发本标题，转发数量加1！");
				result.put("flag", 1);
				result.put("msg", "该用户已转发本标题，转发数量加1！");
			}
			return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	
	/**
	 * PC后台转为资讯
	 * @param topicId
	 * @return
	 * @throws Exception
	 */
	public Integer convertInformationPC(Long topicId,String userId) throws Exception {
		try{
			Map<String,Object> queryMap=new HashMap<>();
			queryMap.put("topicId", topicId);
			queryMap.put("hotType", 11);
			//查询帖子
			List<ForumTopicDto> forumTopicList=ttForumTopicMapper.getTopicList(queryMap);
			ForumTopicDto forumTopicDto=forumTopicList.get(0);
			//帖子标题
			String resultTitle=forumTopicDto.getTopicName();
			resultTitle="【论坛精华】"+resultTitle;
			//logger.info("标题，resultTitle:"+resultTitle);
			//帖子内容
			String resultContent=forumTopicDto.getTopicContent();
			//扫描 1125
			//logger.info("resultContent:"+resultContent);
			resultContent="<p>"+resultContent+"</p>";
			//获取帖子图片路径   
			List<ForumTopicImgDto> forumTopicImgList=forumTopicDto.getForumTopicImgDto();
				if(forumTopicImgList!=null && forumTopicImgList.size()!=0){
					for(ForumTopicImgDto forumTopicImgDto : forumTopicImgList){
						//图片路径
						String contentPath=forumTopicImgDto.getTopicImgPath();
						logger.info("contentPath:"+contentPath);
						
						resultContent =resultContent +"<p><img src='"+contentPath+"' alt='' /></p>";
//			            logger.info("正文内容，resultContent="+resultContent);
			            logger.info("\" 试试 \"");
					}
				}
				
				String resultContentId = FileStore.getInstance().write("nd02", "fs01", "content.txt",
						resultContent.getBytes());
				logger.info("上传文件名：resultContentId："+resultContentId);
				String resultContentUrl = FileStore.getInstance().getDomainURL(resultContentId);
				logger.info("上传文件路径：resultContentUrl："+resultContentUrl);
				Short tagsId=1;
				Short isHot=0;
				String userType="1,2,3";
				Short status=0;
				Date newDate=new Date();
				Short type=0;
				Short contentType=0;
				//String dealerCode=ttForumTopicMapper.queryDealerCode(Integer.valueOf(userId));
				String dealerCode=ttForumTopicMapper.queryDealerCode(99);
				Short isSendWechat=0;
				Short capital=0;
				Short activityType=1;
				Short isArea=1;
				
				Integer newsId=tmNewsActivityInfoMapper.queryNewsId();
				logger.info("新闻资讯ID："+newsId);
				
				TmNewsActivityInfo tmNewsActivityInfo=new TmNewsActivityInfo();
				tmNewsActivityInfo.setNaiId(newsId);
				tmNewsActivityInfo.setTagsId(tagsId);
				tmNewsActivityInfo.setTitile(resultTitle);
				tmNewsActivityInfo.setIsHot(isHot);
				tmNewsActivityInfo.setUserType(userType);
				tmNewsActivityInfo.setStatus(status);
				tmNewsActivityInfo.setContent(resultContentId);
				tmNewsActivityInfo.setCreateDate(newDate);
				tmNewsActivityInfo.setCreateBy(Integer.valueOf(userId));
				tmNewsActivityInfo.setType(type);
				tmNewsActivityInfo.setContentType(contentType);
				tmNewsActivityInfo.setDealerCode(dealerCode);
				tmNewsActivityInfo.setIsSendWechat(isSendWechat);
				tmNewsActivityInfo.setContentPath(resultContentUrl);
				tmNewsActivityInfo.setCapital(capital);
				tmNewsActivityInfo.setActivityType(activityType);
				tmNewsActivityInfo.setIsArea(isArea);
				tmNewsActivityInfoMapper.insertSelective(tmNewsActivityInfo);
				
				logger.info("PC后台转为资讯成功!");
				return newsId;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	
	
	// 将传入时间与当前时间进行对比，是否今天\昨天\前天\同一年  
	//private static String transFormTime(Date date) throws Exception {  
    public String transFormTime(Date date) throws Exception {  
    	
    	try{
    		logger.info("接收的时间date:"+date);
    		
    		Date newDate=new Date();
    		SimpleDateFormat sdf=null;
    		//sdf=new SimpleDateFormat("yyyy-MM-dd 00:00:00");
    		String newDateSDF="yyyy-MM-dd 00:00:00";
    		sdf=new SimpleDateFormat(newDateSDF);
    		String s=sdf.format(newDate);
    		Date newDate2 =  sdf.parse(s);
    		
    		//String yesterDayAMSDF="yyyy-MM-dd 00:00:00";
    		
    		boolean sameYear = false;
            String todySDF = "今天 HH:mm";  
            String yesterDaySDF = "昨天 HH:mm"; 
            String yesterDayAMSDF = "昨天上午 HH:mm";
            String yesterDayPMSDF = "昨天下午 HH:mm";
            String yesterDayNightSDF = "昨天晚上 HH:mm";
            String beforYesterDaySDF = "前天 HH:mm";
            /*String beforYesterDayAMSDF = "前天上午 HH:mm";
            String beforYesterDayPMSDF = "前天下午 HH:mm";
            String beforYesterDayNightSDF = "前天晚上 HH:mm";*/
            String otherSDF = "MM-dd HH:mm";  
            String otherYearSDF = "yyyy-MM-dd HH:mm";  
            SimpleDateFormat sfd = null;  
            String time = "";  
            Calendar dateCalendar = Calendar.getInstance();  
            dateCalendar.setTime(date);  
            Date now = new Date();
            Calendar todayCalendar = Calendar.getInstance();  
            todayCalendar.setTime(now);  
            todayCalendar.set(Calendar.HOUR_OF_DAY, 0);
            todayCalendar.set(Calendar.MINUTE, 0);
      
            if (dateCalendar.get(Calendar.YEAR) == todayCalendar.get(Calendar.YEAR)) {  
                sameYear = true;  
            } else {  
                sameYear = false;  
            }  
      
            if (dateCalendar.after(todayCalendar)) {// 判断是不是今天  
                sfd = new SimpleDateFormat(todySDF);  
                time = sfd.format(date);  
                return time;  
            } else {
                /*todayCalendar.add(Calendar.DATE, -1);  
                if (dateCalendar.after(todayCalendar)) {// 判断是不是昨天  
                	sfd = new SimpleDateFormat(yesterDaySDF);  
                	time = sfd.format(date);  
                    return time; 
                	todayCalendar.add(Calendar.HOUR_OF_DAY, -6);
                    if (dateCalendar.after(todayCalendar)) {// 判断是不是昨天晚上  
                    	sfd = new SimpleDateFormat(yesterDayNightSDF);  
                    	time = sfd.format(date);  
                        return time;  
                    }
                    todayCalendar.add(Calendar.HOUR_OF_DAY, -12);
                    if (dateCalendar.after(todayCalendar)) {// 判断是不是昨天下午  
                    	sfd = new SimpleDateFormat(yesterDayPMSDF);
                    	time = sfd.format(date);  
                        return time;
                    }
                    todayCalendar.add(Calendar.HOUR_OF_DAY, -24);
                    if (dateCalendar.after(todayCalendar)) {// 判断是不是昨天上午
                    	sfd = new SimpleDateFormat(yesterDayAMSDF);
                    	time = sfd.format(date);  
                        return time;  
                    }
                }*/
                todayCalendar.add(Calendar.HOUR, -6);
                if (dateCalendar.after(todayCalendar)) {// 判断是不是昨天晚上  
                	sfd = new SimpleDateFormat(yesterDayNightSDF);  
                	time = sfd.format(date);  
                    return time;  
                }
                todayCalendar.add(Calendar.HOUR, -6);
                if (dateCalendar.after(todayCalendar)) {// 判断是不是昨天下午  
                	sfd = new SimpleDateFormat(yesterDayPMSDF);
                	time = sfd.format(date);  
                    return time;
                }
                todayCalendar.add(Calendar.HOUR, -12);
                if (dateCalendar.after(todayCalendar)) {// 判断是不是昨天上午
                	sfd = new SimpleDateFormat(yesterDayAMSDF);
                	time = sfd.format(date);  
                    return time;  
                }
                //todayCalendar.add(Calendar.HOUR, 0);
                todayCalendar.add(Calendar.DATE, -1);
                if (dateCalendar.after(todayCalendar)) {// 判断是不是前天  
                	sfd = new SimpleDateFormat(beforYesterDaySDF);  
                	time = sfd.format(date);  
                    return time;  
                }
                /*todayCalendar.add(Calendar.HOUR, -30);  
                if (dateCalendar.after(todayCalendar)) {// 判断是不是前天晚上
                	sfd = new SimpleDateFormat(beforYesterDayNightSDF); 
                	time = sfd.format(date);
                    return time;
                }
                todayCalendar.add(Calendar.HOUR, -36); 
                if (dateCalendar.after(todayCalendar)) {// 判断是不是前天下午
                	sfd = new SimpleDateFormat(beforYesterDayPMSDF); 
                	time = sfd.format(date);  
                    return time;  
                }
                todayCalendar.add(Calendar.HOUR, -48);  
                if (dateCalendar.after(todayCalendar)) {// 判断是不是前天上午
                	sfd = new SimpleDateFormat(beforYesterDayAMSDF);  
                	time = sfd.format(date);  
                    return time;  
                }*/
            }  
      
            if (sameYear) {  
                sfd = new SimpleDateFormat(otherSDF);  
                time = sfd.format(date);  
            } else {  
                sfd = new SimpleDateFormat(otherYearSDF);  
                time = sfd.format(date);  
            }  
      
            return time;
    		
    	} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
    }


    /**
     * PC后台发帖
     * @param tmForumTopic
     * @param userId
     * @return
     *//*
	public Map<String, Object> publishTopicPC(TtForumTopic tmForumTopic, String userId) {
		try{
			Map<String, Object> result = new HashMap<String, Object>();
			logger.info("userId:"+userId);
			Date newDate=new Date();
			Short deleteFlag=0;
			tmForumTopic.setPotentialUserId(Long.valueOf(userId));
			tmForumTopic.setUserType(ForumConstant.PC_USER);
			tmForumTopic.setPostTime(newDate);
			tmForumTopic.setIfTop(0L);
			tmForumTopic.setIfEssence(0L);
			tmForumTopic.setCreateBy(Long.valueOf(userId));
			tmForumTopic.setCreateDate(newDate);
			tmForumTopic.setDeleteFlag(deleteFlag);
			ttForumTopicMapper.insertSelective(tmForumTopic);
			result.put("flag", 1);
			result.put("msg", "PC后台发帖成功！");
			return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}*/
    
    
    
    /**
	 * PC后台发帖
	 * @param queryMap
	 * @return
	 */
	public Map<String, Object> publishTopicPC(String userId,TtForumTopic tmForumTopic, HttpServletRequest request)  throws Exception {
		try{
			Map<String, Object> result = new HashMap<String, Object>();
			//定义帖子图片结合
			List<TtForumTopicImg> topicImgList=new ArrayList<TtForumTopicImg>();
			logger.info("获取的userId:"+userId);
			//Long potentialUserId=ttForumTopicMapper.queryPotentialUserId(openId);
			//logger.info("potentialUserId:"+potentialUserId);
			//获取帖子自增ID
			Long topicId=ttForumTopicMapper.queryTopicId();
			logger.info("topicId:"+topicId);
			Date newDate=new Date();
			Long ifTop=0L;
			Long ifessece=0L;
			Short deleteFlag=0;
			//多文件上传
			List<MultipartFile> imgFiles = ((MultipartHttpServletRequest) request)
			        .getFiles("imgFile");
			    MultipartFile imgFile = null;
			    for (int i = 0; i < imgFiles.size(); ++i) {
			    	imgFile = imgFiles.get(i);
			      if (!imgFile.isEmpty()) {
			        try {
			          // 获取上传文件的路径
			          String uploadFilePath = imgFile.getOriginalFilename();
			          logger.info("uploadFilePath:"+uploadFilePath);
			          // 截取上传文件的文件名
			          String uploadFileName = uploadFilePath
			              .substring(uploadFilePath.lastIndexOf('\\') + 1,
			                  uploadFilePath.indexOf('.'));
			          logger.info("uploadFileName:"+uploadFileName);
			          // 截取上传文件的后缀
			          String uploadFileSuffix = uploadFilePath.substring(
			              uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
			          logger.info("uploadFileSuffix:"+uploadFileSuffix);
			          //上传
			          String imgName = FileStore.getInstance().write("nd02", "fs01", uploadFileName+"."+uploadFileSuffix,imgFile.getBytes());
			          logger.info("图片名imgName:"+imgName);
			          String imgURL="";
			          imgURL = FileStore.getInstance().getDomainURL(imgName);
			          logger.info("图片路径imgURL:"+imgURL);
			          logger.info("文件上传成功");
			          TtForumTopicImg tmForumTopicImg=new TtForumTopicImg();
			          tmForumTopicImg.setTopicId(topicId);
			          logger.info("topicId:"+topicId);
			          tmForumTopicImg.setTopicImgPath(imgURL);
			          tmForumTopicImg.setCreateDate(newDate);
			          tmForumTopicImg.setCreateBy(Long.valueOf(userId));
			          logger.info("创建者userId:"+Long.valueOf(userId));
			          topicImgList.add(tmForumTopicImg);
			        } catch (Exception e) {
			        	logger.error(e.getMessage(), e);
						throw new ServiceBizException(e.getMessage(), e);
			        } 
			      } else {
			        logger.info("上传文件为空");
			      }
			    }
			    //保存帖子实体
			    tmForumTopic.setTopicId(topicId);
			    tmForumTopic.setPotentialUserId(Long.valueOf(userId));
			    tmForumTopic.setUserType(ForumConstant.PC_USER);
			    tmForumTopic.setPostTime(newDate);
			    tmForumTopic.setIfTop(ifTop);
			    tmForumTopic.setIfEssence(ifessece);
			    tmForumTopic.setCreateDate(newDate);
			    tmForumTopic.setCreateBy(Long.valueOf(userId));
			    tmForumTopic.setDeleteFlag(deleteFlag);
			    
			    if(!topicImgList.isEmpty() && topicImgList.size()>0){
			    	for(TtForumTopicImg tmFTImg:topicImgList){
			    		ttForumTopicImgMapper.insertSelective(tmFTImg);
			    		logger.info("PC后台保存帖子图片实体完成");
			    	}
			    }
			    ttForumTopicMapper.insertSelective(tmForumTopic);
			    logger.info("PC后台保存帖子实体完成");
			    result.put("flag", 1);
	            result.put("msg", "发帖成功！");
	            return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}


	
	/**
	 * PC后台评论删除
	 * @param userId
	 * @param replyId
	 * @param deleteFlag
	 * @return
	 */
	public Map<String, Object> deleteReplyPC(String userId, Long replyId, Short deleteFlag) {
		try{
			Map<String,Object> result=new HashMap<String, Object>();
			Date newDate=new Date();
			TtForumReply ttForumReply=new TtForumReply();
			ttForumReply.setReplyId(replyId);
			ttForumReply.setDeleteFlag(deleteFlag);
			ttForumReply.setUpdateDate(newDate);
			ttForumReply.setUpdateBy(Long.valueOf(userId));
			ttForumReplyMapper.updateByPrimaryKeySelective(ttForumReply);
			result.put("flag", 1);
            result.put("msg", "PC后台评论状态更新成功！");
            return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}


	/**
	 * PC版块查询
	 * @param typeId
	 * @return
	 */
	public List<TmForumBoard> queryBoardPC(Long typeId) {
		try{
			//Example example = new Example(TmForumBoard.class);
			//example.createCriteria().andCondition("BOARD_TYPE_ID=", typeId);
			//List<TmForumBoard> result = tmForumBoardMapper.selectByExample(example);
			List<TmForumBoard> result = tmForumBoardMapper.queryBoardPC(typeId);
			return result;
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

    public String selectopenIdByUserId(String userId) {
    	String openId = tmForumBoardMapper.selectopenIdByUserId(userId);
    	return openId;
    }
}
